<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="传承人" prop="realName">
          <el-input
            v-model="queryParams.realName"
            placeholder="请输入传承人姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择申请状态" clearable>
          <el-option
            v-for="dict in ich_inheritor_application_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="createdAt">
        <el-date-picker clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['management:InheritorApplication:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['management:InheritorApplication:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['management:InheritorApplication:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['management:InheritorApplication:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="InheritorApplicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="传承人姓名" align="center" prop="realName" />
      <el-table-column label="项目名称" align="center" prop="name" />
      <el-table-column label="申请理由" align="center" prop="reason" />
      <el-table-column label="佐证材料" align="center" width="120">
        <template #default="scope">
          <el-button type="primary" @click="viewProofMaterials(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="相关经历" align="center" prop="experience" />
      <el-table-column label="联系方式" align="center" prop="contact" />
      <el-table-column label="申请状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="ich_inheritor_application_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="审核备注" align="center" prop="remark" />
      <el-table-column label="申请时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleAudit(scope.row)" v-hasPermi="['management:InheritorApplication:edit']">审核</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['management:InheritorApplication:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改传承人申请管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="InheritorApplicationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="项目ID" prop="itemId">
          <el-input v-model="form.itemId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="传承人姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入传承人姓名" />
        </el-form-item>
        <el-form-item label="申请理由" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入申请理由" />
        </el-form-item>
        <el-form-item label="相关经验" prop="experience">
          <el-input v-model="form.experience" type="textarea" placeholder="请输入相关经验" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="申请状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择申请状态">
            <el-option
              v-for="dict in ich_inheritor_application_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入审核备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="审核传承人申请" v-model="auditOpen" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="申请人" prop="realName">
          <el-input v-model="auditForm.realName" disabled />
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="auditForm.name" disabled />
        </el-form-item>
        <el-form-item label="申请状态" prop="status">
          <el-select v-model="auditForm.status" placeholder="请选择申请状态">
            <el-option
              v-for="dict in ich_inheritor_application_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核备注" prop="remark">
          <el-input v-model="auditForm.remark" type="textarea" placeholder="请输入审核备注" />
        </el-form-item>
        <el-form-item label="通过按钮">
          <el-button type="danger" @click="handleApprove" style="width: 100%;">申请通过！</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 佐证材料查看对话框 -->
    <el-dialog title="佐证材料详情" v-model="proofMaterialsDialogVisible" width="800px" append-to-body>
      <div class="proof-materials-content">
        <div v-if="currentProofMaterials && currentProofMaterials.length > 0" class="image-gallery">
          <el-row :gutter="10">
            <el-col :span="8" v-for="(image, index) in currentProofMaterials" :key="index">
              <el-image
                :src="image"
                :preview-src-list="currentProofMaterials"
                :initial-index="index"
                fit="cover"
                style="width: 100%; height: 150px; margin-bottom: 10px; border-radius: 4px;"
                preview-teleported
              />
            </el-col>
          </el-row>
        </div>
        <div v-else style="text-align: center; padding: 50px; color: #999;">
          暂无佐证材料
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="proofMaterialsDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="InheritorApplication">
import { listInheritorApplication, getInheritorApplication, delInheritorApplication, addInheritorApplication, updateInheritorApplication, auditInheritorApplication } from "@/api/management/InheritorApplication"
import { addInheritor } from "@/api/management/inheritor"

const { proxy } = getCurrentInstance()
const { ich_inheritor_application_status } = proxy.useDict('ich_inheritor_application_status')

const InheritorApplicationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const proofMaterialsDialogVisible = ref(false)
const currentProofMaterials = ref([])
const auditOpen = ref(false)
const auditForm = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    name: null,
    realName: null,
    contact: null,
    status: null,
    createdAt: null,
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    itemId: [
      { required: true, message: "项目ID不能为空", trigger: "blur" }
    ],
    realName: [
      { required: true, message: "传承人姓名不能为空", trigger: "blur" }
    ],
    reason: [
      { required: true, message: "申请理由不能为空", trigger: "blur" }
    ],
    contact: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "申请状态不能为空", trigger: "change" }
    ],
    remark: [
      { required: true, message: "审核备注不能为空", trigger: "blur" }
    ],
  }
})

const auditRules = reactive({
  status: [
    { required: true, message: "申请状态不能为空", trigger: "change" }
  ],
  remark: [
    { required: true, message: "审核备注不能为空", trigger: "blur" }
  ]
})

const { queryParams, form, rules } = toRefs(data)

/** 查询传承人申请管理列表 */
function getList() {
  loading.value = true
  listInheritorApplication(queryParams.value).then(response => {
    InheritorApplicationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    itemId: null,
    realName: null,
    reason: null,
    proofMaterials: null,
    experience: null,
    contact: null,
    status: null,
    remark: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("InheritorApplicationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加传承人申请管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getInheritorApplication(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改传承人申请管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["InheritorApplicationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateInheritorApplication(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addInheritorApplication(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除传承人申请管理编号为"' + _ids + '"的数据项？').then(function() {
    return delInheritorApplication(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('management/InheritorApplication/export', {
    ...queryParams.value
  }, `InheritorApplication_${new Date().getTime()}.xlsx`)
}

/** 查看佐证材料 */
function viewProofMaterials(row) {
  // 处理图片数据格式
  if (row.proofMaterials) {
    if (typeof row.proofMaterials === 'string') {
      try {
        // 尝试解析JSON格式
        currentProofMaterials.value = JSON.parse(row.proofMaterials)
      } catch (e) {
        // 如果解析失败，按照逗号分隔的字符串处理
        currentProofMaterials.value = row.proofMaterials.split(',').map(url => url.trim()).filter(url => url)
      }
    } else if (Array.isArray(row.proofMaterials)) {
      currentProofMaterials.value = row.proofMaterials
    } else {
      currentProofMaterials.value = []
    }
  } else {
    currentProofMaterials.value = []
  }
  proofMaterialsDialogVisible.value = true
}

/** 审核按钮操作 */
function handleAudit(row) {
  auditForm.value = {
    id: row.id,
    userId: row.userId,
    itemId: row.itemId,
    realName: row.realName,
    name: row.name,
    experience: row.experience,
    contact: row.contact,
    proofMaterials: row.proofMaterials,
    status: String(row.status), // 确保状态值为字符串类型
    remark: row.remark || ''
  }
  auditOpen.value = true
}

/** 取消审核 */
function cancelAudit() {
  auditOpen.value = false
  auditForm.value = {}
}

/** 提交审核 */
function submitAudit() {
  proxy.$refs["auditFormRef"].validate(valid => {
    if (valid) {
      const updateData = {
        id: auditForm.value.id,
        status: auditForm.value.status,
        remark: auditForm.value.remark
      }
      auditInheritorApplication(updateData).then(response => {
        if (auditForm.value.status === '2') {
          proxy.$modal.msgSuccess("审核成功，已自动添加到传承人列表")
        } else {
          proxy.$modal.msgSuccess("审核成功")
        }
        auditOpen.value = false
        getList()
      }).catch(error => {
        proxy.$modal.msgError("审核失败：" + error.message)
      })
    }
  })
}

/** 直接通过审核 */
function handleApprove() {
  proxy.$modal.confirm('确认通过该传承人申请吗？').then(function() {
    const updateData = {
      id: auditForm.value.id,
      status: '2', // 直接设置为已审核状态
      remark: auditForm.value.remark || '审核通过'
    }
    auditInheritorApplication(updateData).then(response => {
      proxy.$modal.msgSuccess("审核通过，已自动添加到传承人列表")
      auditOpen.value = false
      getList()
    }).catch(error => {
      proxy.$modal.msgError("审核失败：" + error.message)
    })
  }).catch(() => {})
}

getList()
</script>
